<?php


namespace App\Http\Controllers\User\userCenter;


use App\Http\Controllers\Controller;
use App\Services\MemberService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 活动
 * Class ActivateController
 * @package App\Http\Controllers\User\userCenter
 */
class ActivateController extends Controller
{
    /**
     * 获取老兵活动信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function getLbInfo(Request $request)
    {
        $user = $request->userInfo;
        // 今日是否已领取
        $todayGet = DB::table('activate_user_lb_log')
            ->where('unionid', $user->unionid)
            ->whereDate('create_time', '=', date('Y-m-d'))
            ->count();
        if ($todayGet) {
            return successResp(['join'=>false]);
        }
        $maxDays = $this->getMaxNotLoginDays($user->unionid);
        if ($maxDays >= 15) {
            // 使用新的活动
            $lbConf = MemberService::getLbActivateConf();
            if (!array_key_exists($user->level_id, $lbConf)) {
                return successResp(['join'=>false, 'days'=>$maxDays]);
            }
            $newData = [
                'unionid' => $user->unionid,
                'level_id' => $user->level_id,
                'day_num' => $maxDays,
                'get_num' => 0,
                'total_num' => $this->getCanGetNum($maxDays),
                'reward' => json_encode($lbConf[$user->level_id] ?? []),
                'create_time' => date('Y-m-d H:i:s')
            ];
            $id = DB::table('activate_user_lb')->insertGetId($newData);
            $newData['reward'] = $lbConf[$user->level_id] ?? [];
            $newData['id'] = $id;
            return successResp(['join'=>true, 'data' => $newData]);
        }
        // 有没有老活动
        $log = DB::table('activate_user_lb')
            ->where('unionid', $user->unionid)
            ->orderBy('id', 'desc')->first();
        if (!$log) {
            return successResp(['join'=>false, 'days'=>$maxDays]);
        }
        if ($log->get_num >= $log->total_num) {
            return successResp(['join'=>false, 'days'=>$maxDays]);
        }
        $log->reward = json_decode($log->reward, true);
        return successResp(['join'=>true, 'data' => $log]);
    }

    /**
     * 领取老兵奖励
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getLbReward(Request $request)
    {
        $logId = $request->post('id', 0);
        if ($logId <= 0) {
            return errorResp('id empty');
        }
        $user = $request->userInfo;
        // 今日是否已领取
        $todayGet = DB::table('activate_user_lb_log')
            ->where('unionid', $user->unionid)
            ->whereDate('create_time', '=', date('Y-m-d'))
            ->count();
        if ($todayGet) {
            return errorResp('今日已领取奖励，请明日再来');
        }
        $log = DB::table('activate_user_lb')->find($logId);
        if (!$log || $log->unionid != $user->unionid || $log->get_num  >= $log->total_num) {
            return errorResp('活动不存在或者不符合参与条件');
        }
        $reward = json_decode($log->reward, true);
        if (!count($reward)) {
            return errorResp('活动数据异常');
        }
        // 发送奖励
        $num = $reward[$log->get_num] ?? 0;
        if ($num <= 0) {
            return errorResp('活动数据异常1');
        }
        Db::beginTransaction();
        try {
            $lockUser = DB::table('users')->where('id', $user->id)->lockForUpdate()->lock(true)->first();
            MemberService::setMemberBalance(
                $user,
                MemberService::BalanceTypeWf,
                MemberService::FromTypeLBActivity,
                $log->id,
                $num*100,
                '老兵活动领取'
            );
            $re = DB::table('activate_user_lb')->where('id', $log->id)->increment('get_num');
            if (!$re) {
                throw new \Exception('领取失败');
            }
            $re = DB::table('activate_user_lb_log')->insert([
                'activate_id' => $logId,
                'unionid' => $user->unionid,
                'reward_num' => $num,
                'create_time' => date('Y-m-d H:i:s')
            ]);
            if (!$re) {
                throw new \Exception('领取失败1');
            }
        }catch (\Exception $e) {
            DB::rollBack();
            return errorResp($e->getMessage());
        }
        DB::commit();
        return successResp(['id' => $log->id, 'reward'=>$num]);
    }

    /**
     * 获取最后登录时间
     * @param $unionid
     * @return int
     * @throws \Exception
     */
    private function getMaxNotLoginDays($unionid)
    {
        $gameLastTime = DB::table('game_login')
            ->where('unionid', $unionid)
            ->orderBy('id', 'desc')
            ->value('create_time');
        $webLastTime = DB::table('user_login_log')
            ->where('unionid', $unionid)
            ->orderBy('id', 'desc')
            ->offset(1)
            ->value('create_time');
        $lastTime = date('Y-m-d H:i:s');
        if ($gameLastTime) {
            $lastTime = $gameLastTime;
        }
        if ($webLastTime) {
            if ($lastTime == '') {
                $lastTime = $webLastTime;
            } else {
                if (strtotime($webLastTime) > strtotime($gameLastTime)) {
                    $lastTime = $webLastTime;
                }
            }
        }
        $lastDate = new \DateTime($lastTime);
        $now = new \DateTime();
        $days = $now->diff($lastDate)->format('%a');
        return (int)$days;
    }

    /**
     * 获取可领取次数
     * @param $days
     * @return int
     */
    private function getCanGetNum($days)
    {
        if ($days >= 60) {
            return 7;
        } else if ($days >= 30) {
            return 5;
        } else if ($days >= 15) {
            return 3;
        }
        return 0;
    }

    /**
     * 获取今日领取信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function getLevelRewardInfo(Request $request)
    {
        $user = $request->userInfo;
        $levelInfo = DB::table('user_level')->find($user->level_id);
        if (!$levelInfo->day_reward) {
            return successResp(['join' => false]);
        }
        // 最后领取时间
        $lastGetLog = DB::table('activate_level_five_day')
            ->where('unionid', $user->unionid)
            ->orderBy('id', 'desc')->first();
        if ($lastGetLog) {
            $lastDate = new \DateTime($lastGetLog->create_time);
            $now = new \DateTime();
            $days = $now->diff($lastDate)->format('%a');
            if ((int)$days < 5) {
                return successResp(['join' => true, 'can_get' => false, 'reward' => $levelInfo->day_reward, 'days' => 5-$days]);
            }
        }
        return successResp(['join' => true, 'can_get' => true, 'reward' => $levelInfo->day_reward]);
    }

    /**
     * 领取等级兑换券
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function getLevelReward(Request $request)
    {
        $user = $request->userInfo;
        $levelInfo = DB::table('user_level')->find($user->level_id);
        if (!$levelInfo->day_reward) {
            return errorResp('不符合活动条件');
        }
        // 最后领取时间
        $lastGetLog = DB::table('activate_level_five_day')
            ->where('unionid', $user->unionid)
            ->orderBy('id', 'desc')->first();
        if ($lastGetLog) {
            $lastDate = new \DateTime($lastGetLog->create_time);
            $now = new \DateTime();
            $days = $now->diff($lastDate)->format('%a');
            if ((int)$days < 5) {
                return errorResp('不到领取时间');
            }
        }
        $expireDay = DB::table('sys_config')
            ->where('key', 'five_day_expire')
            ->value('value');
        $reward = $levelInfo->day_reward;
        $log = [
            'unionid' => $user->unionid,
            'get_num' => $reward,
            'level_id' => $user->level_id,
            'status' => 1,
            'expired_time' => date('Y-m-d H:i:s', time()+$expireDay*86400),
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
        ];
        try {
            $lockUser = DB::table('users')->where('id', $user->id)->lockForUpdate()->lock(true)->first();
            $re = DB::table('activate_level_five_day')->insert($log);
            if (!$re) {
                throw new \Exception('领取失败');
            }
        }catch (\Exception $e) {
            DB::rollBack();
            return errorResp($e->getMessage());
        }
        DB::commit();
        return successResp('领取成功');
    }

    /**
     * 获取兑换券列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getLevelDhqList(Request $request)
    {
        $user = $request->userInfo;
        $w = [
            ['unionid', '=', $user->unionid]
        ];
        if ($request->get('status', '')) {
            $w[] = ['status', '=', $request->get('status', '')];
        }
        $list = DB::table('activate_level_five_day')
            ->where($w)
            ->orderBy('id', 'desc')
            ->paginate(10);
        foreach ($list as &$item) {
            if ($item->status != 2 && strtotime($item->expired_time) < time()) {
                $item->status = 3; // 已过期
            }
        }
        return successResp($list);
    }

    /**
     * 使用兑换券
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function useLevelDhq(Request $request)
    {
        //验证表单
        $this->validate($request, [
            'id' => ['required','int'],
        ]);
        $user = $request->userInfo;
        try {
            $log = DB::table('activate_level_five_day')->where('id', $request->id)->lockForUpdate()->lock(true)->first();
            if (!$log || $log->unionid != $user->unionid || $log->status != 1) {
                throw new \Exception('券信息错误或已兑换');
            }
            if (strtotime($log->expired_time) < time()) {
                throw new \Exception('券已过期');
            }
            MemberService::setMemberBalance(
                $user,
                MemberService::BalanceTypeWf,
                MemberService::FromTypeFiveDayActivity,
                $log->id,
                $log->get_num * 100,
                '会员等级活动领取'
            );
            $re = DB::table('activate_level_five_day')
                ->where('id', $request->id)
                ->update(['status' => 2, 'update_time'=>date('Y-m-d H:i:s')]);
            if (!$re) {
                throw new \Exception('兑换失败');
            }
        }catch (\Exception $e) {
            DB::rollBack();
            return errorResp($e->getMessage());
        }
        DB::commit();
        return successResp($log);
    }
}
